package pub.devrel.easypermissions;

import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.window.dialog.CommonDialog;
import ohos.agp.window.dialog.IDialog;
import ohos.app.AbilityContext;

public class AppSettingsDialogHolderAbility extends Ability implements IDialog.ClickedListener {
    private static final int APP_SETTINGS_RC = 7534;

    private CommonDialog mDialog;
    private int mIntentFlags;

    public static Intent createShowDialogIntent(AbilityContext context, AppSettingsDialog dialog) {
        Intent intent = new Intent();
        Operation operation = new Intent.OperationBuilder()
            .withDeviceId("")
            .withBundleName("pub.devrel.easypermissions")
            .withAbilityName("pub.devrel.easypermissions.AppSettingsDialogHolderAbility")
            .build();
        intent.setParam(AppSettingsDialog.EXTRA_APP_SETTINGS, dialog);
        intent.setOperation(operation);
        return intent;
    }

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        AppSettingsDialog appSettingsDialog = AppSettingsDialog.fromIntent(getIntent(), this);
        mIntentFlags = appSettingsDialog.getIntentFlags();
        mDialog = appSettingsDialog.showDialog(this, this);
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mDialog != null && mDialog.isShowing()) {
            mDialog.destroy();
        }
    }

    @Override
    public void onClick(IDialog dialog, int which) {
        if (which == dialog.BUTTON1) {
            Intent intent = new Intent();
            Operation operation = new Intent.OperationBuilder()
                .withDeviceId("")
                .withBundleName("pub.devrel.easypermissions")
                .withAbilityName("pub.devrel.easypermissions.AppSettingsDialogHolderAbility")
                .build();
            intent.setOperation(operation);
            intent.setFlags(mIntentFlags);
            startAbilityForResult(intent, APP_SETTINGS_RC);
        } else if (which == dialog.BUTTON3) {
            onStop();
        } else {
            throw new IllegalStateException("Unknown button type: " + which);
        }
    }

    @Override
    protected void onAbilityResult(int requestCode, int resultCode, Intent data) {
        super.onAbilityResult(requestCode, resultCode, data);
        setResult(resultCode, data);
        onStop();
    }
}
